<template>
	<view>
		<u-sticky bgColor="#fff" v-if="!isUnauthorized">
			<view class="blank10"></view>
			<view class="flex wrapper">
				<view class="">
					<picker mode="multiSelector" :range="picker_range" :value="picker_value" @change="bind_picker_change">
					<view class="btn-date flex">
						<view class="mr10 text-primary">
							{{y_m}}
						</view>
						<u-icon name="arrow-down" size="14" color="#675f91"></u-icon>
					</view>
					</picker>
				</view>
				<view class="flex-1">
					销售及成本
				</view>
				<view class="ml10" v-if="isBoss && openFlag">
						<u-button type="info" size="small" text="折叠" @click="close"></u-button>
				</view>
				<view class="ml10" v-if="isBoss && !openFlag">
						<u-button type="info" size="small" text="展开" @click="open"></u-button>
				</view>
			</view>
			<view class="blank10"></view>
			<view class="bg-gray">
				<view class="blank20"></view>
				<view class="flex justify-between">
					<template v-for="col in tableHd">
							<view :style="[col.style]">
								<view class="text-gray font-24 flex" v-if="col.key == 'date'" @click="bind_sort_date">
									<text class="ml15">{{col.title}}</text>
									<u-icon name="arrow-upward" size="14" color="#675f91" v-if="sortType == 'asc'"></u-icon>
									<u-icon name="arrow-downward" size="14" color="#675f91" v-if="sortType == 'desc'"></u-icon>
								</view>
								<view class="text-right text-gray font-24" v-else>
									{{col.title}}
								</view>
							</view>
					</template>
				</view>
				<view class="blank20"></view>
			</view>
		</u-sticky>
		
		<template v-if="isUnauthorized">
			<unauthorized></unauthorized>
		</template>
		<template v-else>
			<nodata v-if="loadingStatus == 'nodata'"></nodata>
			
			<view class="" v-if="isBoss">
				<view class="" v-for="(v,i) in list">
					<dataItem :detail="v" :table="tableHd" :open="openFlag" @toggle="itemToggle"></dataItem>
				</view>
			</view>
			
			<view class="bgw" v-if="!isBoss">
				<view class="" v-for="(v,i) in list" @click="reportDetail(v)">
					<view class="blank20"></view>
					<view class="flex justify-between">
						<template v-for="col in tableHd">
							<view :style="[col.style]">
								<view v-if="col.key == 'date'">
									<text class="ml15 font-bold">
										{{v.date | filterDate}}
									</text>
								</view>
								<view class="flex" style="justify-content: center;" v-else-if="col.key == 'note'">
									<u-icon name="arrow-right" color="#999999" size="12"></u-icon>
								</view>
								<view class="text-right" v-else-if="col.isRatio">
									{{v[col.key] | formatPrice}}%
								</view>
								<view class="text-right" v-else>
									{{v[col.key] | formatPrice}}
								</view>
							</view>
						</template>
					</view>
					<view class="blank20"></view>
					<u-line dashed></u-line>
				</view>
			</view>
			<view class="blank"></view>
			<!-- style="bottom: 50px;" -->
			<view class="fixed-bottom bgw">
				<u-line></u-line>
				<view class="blank20"></view>
				<view class="flex justify-between">
					<template v-for="col in tableHd">
						<view :style="[col.style]">
							<view class="" v-if="col.key == 'date'">
								<text class="ml15 text-gray">汇总</text>
							</view>
							<view class="flex" style="justify-content: center;" v-else-if="col.key == 'note'">
							</view>
							<view class="text-right" v-else-if="col.isRatio">
								{{sum[col.key] | formatPrice}}%
							</view>
							<view class="text-right font-bold" v-else>
								{{sum[col.key] | formatPrice}}
							</view>
						</view>
					</template>
				</view>
				<view class="blank20"></view>
			</view>
		</template>
	</view>
</template>

<script>
	import {
		day_kpi_report
	} from '@/common/api.js';
	import dataItem from './components/data-item.vue';
	import unauthorized from '@/components/unauthorized.vue';
	import nodata from '@/components/nodata.vue';
	
	
	const _today = new Date();
	let _today_year = _today.getFullYear();
	let _today_month = _today.getMonth() + 1;
	let _today_day = _today.getDate();

	export default {
		components: {
			dataItem,unauthorized,nodata
		},
		data() {
			return {
				role:null,
				list: [],
				y_m: _today_year + '-' + (_today_month>10?_today_month:'0'+_today_month),
				tableConfig:{
					date:{
						title: '日期',
						key: 'date',
						style: {
							width:'210rpx'
						}
					},
					day_cost_amount:{
						title: '成本',
						key: 'day_cost_amount',
						style: {
							flex:1,
						}
					},
					day_sales_amount:{
						title: '销售额',
						key: 'day_sales_amount',
						style: {
							flex:1
						}
					},
					day_cost_ratio:{
						title: '成本比例',
						key: 'day_cost_ratio',
						style: {
							flex:1
						},
						isRatio:true
					},
					day_gross_profit_ratio:{
						title: '毛利率',// day_gross_profit 毛利
						key: 'day_gross_profit_ratio',
						style: {
							flex:1
						},
						isRatio:true
					},
					note:{
						title: '',
						key: 'note',
						style: {
							width:'100rpx'
						}
					}
				},
				tableHd: [],
				picker_value: [0, _today_month - 1],
				isBoss:false,
				sortType:'desc',//asc升序  desc降序
				sum:{}, //汇总数据
				isUnauthorized:false, //无权限
				loadingStatus:'',
				openFlag:false,
				openItemFlag:{}
			}
		},
		filters:{
			
		},
		computed: {
			picker_range() {
				let arr = [
					[],
					[]
				];
				for (let i = 0; i < 3; i++) {
					arr[0].push(_today_year - i);
				}
				for (let i = 1; i < 13; i++) {
					if(i>9){
						arr[1].push(i);
					}else{
						arr[1].push('0'+i);
					}
				}
				return arr;
			}
		},
		methods: {
			itemToggle(flag,date){
				let num = 0;
				this.openItemFlag[date] = flag;
				if(flag){
					for(let date in this.openItemFlag){
						if(this.openItemFlag[date]){
							num++
						}
					}
					if(num == this.list.length){
						this.openFlag = true;
					}
				}
				if(!flag){
					for(let date in this.openItemFlag){
						if(!this.openItemFlag[date]){
							num++
						}
					}
					if(num == this.list.length){
						this.openFlag = false;
					}
				}
			},
			bind_picker_change(e) {
				let value = e.detail.value;
				this.picker_value = value;
				// console.log(this.picker_range);
				let new_y_m = this.picker_range[0][value[0]] + '-' + this.picker_range[1][value[1]];
				if(this.y_m != new_y_m){
					this.y_m = new_y_m;
					this.getData();
				}
			},
			bind_sort_date(){
				if(this.sortType =='desc'){
					this.sortType ='asc';
				}else{
					this.sortType ='desc';
				}
				this.list = this.sort_list(this.list);
			},
			sort_list(list){
				list = list.sort((a,b)=>{
					let a_time = new Date(a.date).getTime();
					let b_time = new Date(b.date).getTime();
					if(this.sortType =='desc'){
						return b_time - a_time;
					}else{
						return a_time - b_time;
					}
				});
				return list;
			},
			open(){
				this.openFlag = true;
			},
			close(){
				this.openFlag = false;
			},
			reportDetail(v){
				let date = v.date;
				let cost_center_id = v.cost_center_id[0];
				let cost_center_id_name = v.cost_center_id[1];
				let cus_group_id_name = v.cus_group_id[1]||'';
				let cus_group_id = v.cus_group_id[0]||0;
				this.nav('/reportDetail/reportDetail?date=' + date + '&cost_center_id='+cost_center_id +'&cost_center_id_name='+cost_center_id_name+'&cus_group_id_name='+cus_group_id_name+'&cus_group_id='+cus_group_id);
			},
			getData() {
				uni.showLoading({
					title: '加载中',
					mask:true
				});
				this.loadingStatus = 'loading';
				day_kpi_report({
					month:this.y_m.replace('-','')
				},{custom:{catch:true}}).then((res) => {
					this.isUnauthorized = false;
					let tableHd = [];
					res.result['字段列表'].forEach(k=>{
						if(this.tableConfig[k]){
							tableHd.push(this.tableConfig[k])
						}
					})
					tableHd.push(this.tableConfig.note);
					// console.log(tableHd);
					this.tableHd = tableHd;
					
					let list = [];
					//day_sales_price 餐标
					if(this.isBoss){
						let list_obj = {};
						res.result['销售成本'].forEach(v=>{
							!list_obj[v.date] && (list_obj[v.date] = []);
							v.day_cost_ratio = v.day_cost_ratio*100;
							v.day_gross_profit_ratio = v.day_gross_profit_ratio*100;
							list_obj[v.date].push(v);
						})
						for(let date in list_obj){
							let sum_item = {
								day_cost_amount: 0,
								// day_cost_ratio: 0,
								day_gross_profit: 0,
								// day_gross_profit_ratio:0,
								day_sales_amount:0
							};
							list_obj[date].forEach(v=>{
								for(let key in sum_item){
									sum_item[key] += v[key]||0;
								}
							})
							if(!sum_item.day_sales_amount){
								sum_item.day_cost_ratio = 0;
								sum_item.day_gross_profit_ratio = 0;
							}else{
								sum_item.day_cost_ratio = sum_item.day_cost_amount/sum_item.day_sales_amount*100;
								sum_item.day_gross_profit_ratio = (sum_item.day_sales_amount-sum_item.day_cost_amount)/sum_item.day_sales_amount*100;
							}
							// list_obj[date].push({
							// 	cost_center_id:[335, "央厨"],
							// 	cus_group_id:false
							// })
							let childs = list_obj[date].sort((a,b)=>{
								let a_sort_num = a.cus_group_id ? a.cus_group_id[0]*10000:0;
								let b_sort_num = b.cus_group_id ? b.cus_group_id[0]*10000:0;
								a_sort_num += a.cost_center_id[0];
								b_sort_num += b.cost_center_id[0];
								return b_sort_num - a_sort_num;
							});
							list.push({
								date:date,
								childs:childs,
								...sum_item
							})
						}
					}else{
						res.result['销售成本'].forEach(v=>{
							v.day_cost_ratio = v.day_cost_ratio*100;
							v.day_gross_profit_ratio = v.day_gross_profit_ratio*100;
						})
						list = res.result['销售成本'];
					}
					list = this.sort_list(list);
					this.list = list;
					// console.log(list);
					let sum = {
						day_cost_amount: 0,
						// day_cost_ratio: 0,
						day_gross_profit: 0,
						// day_gross_profit_ratio:0,
						day_sales_amount:0
					};
					list.forEach(v=>{
						for(let key in sum){
							sum[key] += v[key]||0;
						}
					})
					if(!sum.day_sales_amount){
						sum.day_cost_ratio = 0;
					}else{
						sum.day_cost_ratio = sum.day_cost_amount/sum.day_sales_amount*100;
					}
					if(!sum.day_sales_amount){
						sum.day_gross_profit_ratio = 0;
					}else{
						sum.day_gross_profit_ratio = (sum.day_sales_amount-sum.day_cost_amount)/sum.day_sales_amount*100;
					}
					
					this.sum = sum;
					
					if(this.list.length == 0){
						this.loadingStatus = 'nodata';
					}else{
						this.loadingStatus = 'end';
					}
				}).catch((res) => {
					this.loadingStatus = 'end';
					try{
						if(res.error.data.message == '需要先开通报表权限。'){
							this.isUnauthorized = true;
						}
					}catch(e){
						
					}
				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},

		},
		onLoad(d) {
			try{
				this.role = this.$store.getters.get_role;
				// let isUnauthorized = false;
				// if(!this.role['报表模块']['成本'].read && !this.role['报表模块']['销售'].read){
				// 	isUnauthorized = true;
				// }
				// this.isUnauthorized = isUnauthorized;
				
				this.userInfo = this.$store.getters.get_userInfo;
				// this.isBoss = this.userInfo.cost_center_category_list.length > 1;
				this.isBoss = true;
				// console.log(this.role['报表模块']['销售']);
				// console.log(this.userInfo);
				this.getData();
			}catch(e){
				uni.reLaunch({
				    url: '/pages/login/login'
				});
			}
		},
		onShow() {
			uni.$off('refresh_report');
			uni.$once('refresh_report',()=>{
				this.getData();
			})
		},
		onReady() {},
		onPullDownRefresh() {
			this.getData();
		}
	}
</script>

<style lang="scss" scoped>
	.blank{
		height: 90upx;
	}
	.fixed-bottom{
		bottom: var(--window-bottom);
	}
	/deep/.item {
		padding: 20upx 20upx;
	}

	/deep/.food-box {
		margin: 0 20upx 0 20upx;
		background-color: #ededed;
		padding: 0;
	}

	/deep/.food-box .item {
		padding: 10upx 10upx;
	}

	/deep/.active.time-item-box {
		position: relative;
		// border: 1px solid #675f91;
		// border-top: 1px solid #675f91;
		border-bottom: 1px solid #675f91;
	}

	/deep/.time-box::before {
		// position: absolute;
		// content: ' ';
		// width: 2px;
		// height: 100%;
		// top: 0;
		// bottom: 0;
		// left: 2upx;
		// background-color: #675f91;
	}

	/deep/ .icon-btn {
		padding: 3px;
		border: 1px solid #d9d9d9;
		border-radius: 50%;
	}

	/deep/ .icon-btn.active {
		background-color: #675f91;
		border-color: #675f91;
	}
	.btn-date{
		// border: 1px solid #675f91;
		padding: 14upx 20upx 14upx 0;
		border-radius: 8upx;
		font-weight: bold;
		margin-right: 15upx;
	}
	
</style>